package com.ist.smartmonitor.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.MapTypeControl;
import com.google.gwt.maps.client.control.SmallMapControl;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.ist.smartmonitor.shared.AbstractDto;
/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SmartMonitor implements EntryPoint {
	
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	private MapWidget mapWiget;
	
//	<longitude>-9.138041518911002</longitude>
//	<latitude>38.73802131443526</latitude>
//	<altitude>0</altitude>
	
	public void startPolling() {
		greetingService.getObj(new AsyncCallback<AbstractDto>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("EXCEPTION CAUGHT");
				startPolling();
			}

			@Override
			public void onSuccess(AbstractDto result) {
//				updateClinteInfo(result);
				System.out.println("GOT DATA");
				startPolling();
			}
		});
	}
	
//	private void updateClinteInfo(Double[] result) {
//		mapWiget.addOverlay(new Marker(LatLng.newInstance(result[0], result[1])));
//	}
	
	public void onModuleLoad() {		
		loadMap();
		startPolling();
	}

	private void loadMap() {
		Maps.loadMapsApi("", "2", false, new Runnable() {
			public void run() {
				final StringBuilder widthString = new StringBuilder();
				widthString.append(Window.getClientWidth());
				widthString.append("px");
				final StringBuilder heightString = new StringBuilder();
				heightString.append(Window.getClientHeight());
				heightString.append("px");
				mapWiget = new MapWidget(LatLng.newInstance(
						38.73802131443526, -9.138041518911002), 15);
				mapWiget.setSize(widthString.toString(), heightString
						.toString());

				mapWiget.addControl(new SmallMapControl());
				mapWiget.addControl(new MapTypeControl());	
				

//				mapWiget.addMapClickHandler(new MapClickHandler() {
//					public void onClick(MapClickEvent e) {
//						MapWidget sender = e.getSender();
//						Overlay overlay = e.getOverlay();
//						LatLng point = e.getLatLng();
//						
//
//						if (overlay != null && overlay instanceof Marker) {
////							sender.removeOverlay(overlay);
//							mapWiget.removeOverlay(overlay);
//						} else {
////							sender.addOverlay(new Marker(point));
//							mapWiget.addOverlay(new Marker(point));
//						}
//					}
//				});

				RootPanel.get().add(mapWiget);
			}
		});
	}
	
}
